# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: util_redis.py
@time: 2024/11/5 23:00 
@desc: 

"""
import redis
from config import REDIS_CONF
from sdk.utils.util_secret import JwtHandler
from config import sk

jh = JwtHandler(secret=sk)


class Redis(object):
    """
    Redis
    """
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        self.r = None
        self.init_redis()

    def init_redis(self):
        """

        :return:
        """
        if not self.r:
            self.r = redis.Redis(host=REDIS_CONF["host"], port=REDIS_CONF["port"], db=REDIS_CONF["db"],
                                 decode_responses=True)
        return self.r

    def add_token_redis(self, token):
        """

        :param token:
        :return:
        """
        try:
            self.init_redis()
            self.r.sadd('logout', token)
            return True
        except:
            return False

    def check_exists_redis(self, token):
        """

        :param token:
        :return:
        """
        self.init_redis()
        return self.r.sismember('logout', token)

    def delete_token_redis(self, token):
        """

        :param token:
        :return:
        """
        self.init_redis()
        self.r.srem('logout', token)

    def check_token_redis(self):
        """
        检查并删除已过期的cookies
        :return:
        """
        members = self.r.smembers('logout')
        decoded_members = {member.decode('utf-8') for member in members}
        for token in decoded_members:
            if not jh.decrypt_token(token=token):
                self.r.srem('logout', token)
